import java.util.Scanner;
import java.util.concurrent.*;

class MyBlockingQueue{
    private  String[] items=new String[1000];
    //队列的头
    private  volatile int head=0;
    //描述队列的下一个元素，也就是正常队列的队尾
    private volatile int tail=0;
    //统计多少个数量
    public  volatile int size=0;
    //插入
    public void put(String elem) throws InterruptedException {
        synchronized (this) {
            if(size >= items.length) {
                this.wait();               //1号
            }

            items[tail] = elem;
            tail++;
            if (tail >= items.length) {
                tail = 0;
            }
            size++;
            this.notify();                //2号
        }
    }
    //取出队头元素
    public String take() throws InterruptedException {
        synchronized (this) {
            if (size == 0) {
                this.wait();            //3号
            }
            String elem = items[head];
            head++;
            if (head > items.length) {
                head = 0;
            }
            size--;
            this.notify();              //4号
            return elem;
        }
    }
}
public  class  Demo {
    public static void main(String[] args)  {
       MyBlockingQueue myBlockingQueue=new MyBlockingQueue();
        Thread t1=new Thread(()->{
            int count =0;
            while (true){
                try {
                    myBlockingQueue.put(String.valueOf(count));
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("生产了元素"+count);
                count++;

            }
        });
        Thread t2=new Thread(()->{
            while(true) {
                Integer n = null;
                try {
                    n = Integer.valueOf(myBlockingQueue.take());
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("消费者" + n);
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        t1.start();
        t2.start();
    }
}